﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.MenuCommand;
using MediatR;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

namespace D.Medicalcare.Write.API.Application.Handlers.MenuHandler
{
    public class DelsMenuHandler : IRequestHandler<DelsMenuCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Menu> menuRep;

        public DelsMenuHandler(IBaseRepository<Menu> menuRep)
        {
            this.menuRep = menuRep;
        }

        public async Task<APIResult<object>> Handle(DelsMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var menu = await menuRep.GetModel(request.MenuId);
            if (menu == null)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "删除失败，菜单不存在";
                return await Task.FromResult(result);
            }

            // 检查是否为父级菜单
            if (menu.ParentId == 0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "删除失败，不能删除父级菜单";
                return await Task.FromResult(result);
            }
            else
            {
                await GetMenus(menu);
                result.Code = APIEnum.Success;
                result.Msg = "删除成功";
                result.Data = 1;
                return await Task.FromResult(result);
            }

        }

        public async Task GetMenus(Menu menu)
        {
            menu.IsDeleted = true;
            await menuRep.Update(menu);
            var m = menuRep.GetAll().Where(x => x.ParentId == menu.MenuId);
            foreach (var item in m)
            {
                await GetMenus(item);
            }
        }
    }
}